13  R: Recursion

13.1 Recursion

Recursion is a method of solving a problem by dividing it into smaller instances of the same problem. Recursion solves such problems by using functions that call themselves from within their own code.

Below is an example, where we defined a function that computes the factorial of a number by recursion.

factorial<-function(n)
{
  if(n==1){return(1)}else(return(n*factorial(n-1)))
}
factorial(5)
[1] 120

13.1.1 Practice exercise 1

Use recursion to write a function that accepts a word as an argument, and returns TRUE if the word is a palindrome, otherwise returns FALSE.